package mathive.client.panels;


import mathive.client.TestService;
import mathive.client.TestServiceAsync;

import com.google.gwt.core.client.GWT;
import com.google.gwt.event.dom.client.ClickEvent;
import com.google.gwt.event.dom.client.ClickHandler;
import com.google.gwt.user.client.Window;
import com.google.gwt.user.client.rpc.AsyncCallback;
import com.google.gwt.user.client.ui.Button;
import com.google.gwt.user.client.ui.HasHorizontalAlignment;
import com.google.gwt.user.client.ui.HorizontalPanel;
import com.google.gwt.user.client.ui.Label;
import com.google.gwt.user.client.ui.ScrollPanel;
import com.google.gwt.user.client.ui.VerticalPanel;
import com.google.gwt.user.client.ui.Widget;

public class TestsPanel {
	private static final TestServiceAsync SERVICE = GWT.create(TestService.class);

	VerticalPanel mainPanel = new VerticalPanel();
	private VerticalPanel testsPanel = new VerticalPanel();
	private ScrollPanel scrollPanel = new ScrollPanel(testsPanel);
	private String[] avaibleTests;

	public TestsPanel(){
		scrollPanel.setSize("350px", "200px");

	}

	public Widget getPanel(){
		mainPanel.clear();
		initialize();
		return mainPanel;
	}

	public void initialize() {
		SERVICE.getAvaibleTests(new AvaibleTestsResponse());

		mainPanel.add(new Label("Loading..."));
	}

	private class AvaibleTestsResponse implements AsyncCallback<String[]> {
		@Override
		public void onFailure(Throwable caught) {
		}

		@Override
		public void onSuccess(String[] result) {
			testsPanel.clear();
			mainPanel.clear();
			mainPanel.setHorizontalAlignment(HasHorizontalAlignment.ALIGN_CENTER);
			mainPanel.add(scrollPanel);

			avaibleTests = new String[result.length];
			for (int i = 0; i < result.length; i++) {
				testsPanel.add(new AvaibleTest(result[i], i));
			}

		}
	}

	private class AvaibleTest extends HorizontalPanel {
		private int indexx;
		private Button startButton;

		public AvaibleTest(String info, int index) {
			indexx = index;
			startButton = new Button("Start test");

			final String name = info.substring(0, info.indexOf(' '));

			avaibleTests[index] = name;

			add(new Label(info));
			add(startButton);
			startButton.addClickHandler(new ClickHandler() {
				public void onClick(ClickEvent event) {
					mainPanel.clear();
					mainPanel.add(new PlayTestPanel(avaibleTests[indexx]));
				}
			});
		}
	}
}
